package com.example.demo.app;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v4.widget.DrawerLayout;

import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;


import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.demo.app.R;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.Ack;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.okhttp.Request;

public class MainActivity extends Activity {

    ActionBarDrawerToggle tog;

    String TAG = "tt_Demo";
    View leftView;
    DrawerLayout dar;
    Socket mSocket;

    EditText edit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dar = (DrawerLayout) findViewById(R.id.drawer);

        edit  = (EditText)findViewById(R.id.msg_edit);
        leftView  = findViewById(R.id.left_view);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new Click());
        tog = new ActionBarDrawerToggle(this,dar,R.drawable.tt,R.string.open,R.string.close){


            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        };

        dar.setDrawerListener(tog);


        TextView v;

        //配置异步加载


        ImageLoaderConfiguration.Builder Ω = new ImageLoaderConfiguration
                .Builder(this);
        Ω.memoryCacheExtraOptions(480, 800);
        Ω.discCacheExtraOptions(480, 800, Bitmap.CompressFormat.JPEG, 75, null);
        Ω.threadPoolSize(3);
        Ω.threadPriority(Thread.NORM_PRIORITY - 2);
        Ω.denyCacheImageMultipleSizesInMemory();
        Ω.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024));
        Ω.memoryCacheSize(2 * 1024 * 1024);
        Ω.discCacheSize(50 * 1024 * 1024);
        Ω.discCacheFileNameGenerator(new Md5FileNameGenerator());
        Ω.tasksProcessingOrder(QueueProcessingType.LIFO);
        Ω.discCacheFileCount(100);
        Ω.discCache(new UnlimitedDiscCache(Environment.getExternalStorageDirectory()));
        Ω.defaultDisplayImageOptions(DisplayImageOptions.createSimple());
        Ω.imageDownloader(new BaseImageDownloader(this, 5 * 1000, 30 * 1000));
        Ω.writeDebugLogs();
        ImageLoaderConfiguration config = Ω.build();


        ImageLoader.getInstance().init(config);
        //异步加载图片


        DisplayImageOptions options;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_launcher) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
                //.considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
                        // .decodingOptions(android.graphics.BitmapFactory.Options.d)//&#x8bbe;&#x7f6e;&#x56fe;&#x7247;&#x7684;&#x89e3;&#x7801;&#x914d;&#x7f6e;
                //.delayBeforeLoading(int delayInMillis)//int delayInMillis为你设置的下载前的延迟时间
                //设置图片加入缓存前，对bitmap进行设置
                //.preProcessor(BitmapProcessor preProcessor)
                .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成

        ImageLoader il = ImageLoader.getInstance();
        ImageView imageView = (ImageView) findViewById(R.id.image);


        il.displayImage("http://cdn.iknow.bdimg.com/static/question/widget/user/info/daily/img/daily_0a85179.png",imageView,options);


    }



    public void startSocket(){
        try {

            mSocket = IO.socket("");


            mSocket.on(Socket.EVENT_RECONNECT, onReConnect);
            mSocket.on(Socket.EVENT_DISCONNECT, onDisConnect);
            mSocket.on(Socket.EVENT_MESSAGE, onMessage);
            mSocket.on(Socket.EVENT_CONNECT, onConnect);
            mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
            mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);

            mSocket.on("dataListener", dataListener);
            mSocket.connect();



        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭socket
     */
    public void stopSocket(){
        try{
            if (mSocket == null) {
                //startConnect();
                return;
            }

            if (mSocket != null) {
                mSocket.disconnect();
                mSocket.off(Socket.EVENT_DISCONNECT, onDisConnect);
                mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
                mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
                mSocket.off(Socket.EVENT_MESSAGE, onMessage);
                mSocket.off(Socket.EVENT_CONNECT, onConnect);
                mSocket.off("dataListener", dataListener);


            }
            mSocket.close();
            mSocket = null;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  发送消息
     * @param msg
     */
    public void sendMessage(String msg){
        try{

            if(mSocket != null){

                mSocket.emit("dataListener", msg, new Ack() {
                    @Override
                    public void call(Object... objects) {

                        //回调信息
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private Emitter.Listener dataListener = new Emitter.Listener(){


        @Override
        public void call(Object... objects) {

        }
    }  ;


    private Emitter.Listener onReConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.e(TAG, "正在重连==" + args[0].toString());
        }
    };

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.e(TAG, "连接错误==" + args[0].toString());
        }
    };
    private Emitter.Listener onDisConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            if (mSocket != null) {
                Log.e(TAG, "连接断开" + mSocket.connected());
            }
        }
    };

    private Emitter.Listener onMessage = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.e(TAG, "===" + args.toString());
        }
    };
    private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.e(TAG, "===" + args.toString());
        }
    };
    class Click implements  View.OnClickListener{

        @Override
        public void onClick(View v) {


            switch (v.getId()){
                case R.id.button:

                    if(dar.isDrawerOpen(leftView)){
                        dar.closeDrawer(leftView);
                    }else{
                        dar.openDrawer(leftView);
                    }

                    break;
                case R.id.start_button:

                    startSocket();
                    break;
                case R.id.stop_button:

                    startSocket();
                    break;
                case R.id.send_button:

                    sendMessage(edit.getText().toString());
                    break;



            }

        }
    }


}
